<template>
    <div class="assess_form facial_nerve">
        <div class="form_title">XXXX医疗机构</div>
        <div class="form_name">周围性面神经炎治疗成绩评分表</div>
        <div class="form_patient_bar">
            <div v-for="(item, index) in patientStruct" :key="index" class="patient_info_item">
                <div class="item_label">{{ item.label }}：</div>
                <div class="item_value">{{ formType == 'template' ? item.label : patientInfo[item.key] }}{{ item.unit }}</div>
            </div>
        </div>
        <el-form ref="assessForm" :model="selfFormData" :rules="rules" label-width="85px">
            <el-form-item label="通讯地址：" prop="addr">
                <el-input v-if="formType === 'edit' || formType === 'template'" placeholder="通讯地址" v-model="selfFormData.addr" :disabled="stage !== 1 || formType === 'template'" />
                <span v-else>{{ selfFormData.addr }}</span>
            </el-form-item>
            <el-form-item label="联系方式：" prop="phoneNum">
                <el-input v-if="formType === 'edit' || formType === 'template'" placeholder="联系方式" v-model="selfFormData.phoneNum" :disabled="stage !== 1 || formType === 'template'" />
                <span v-else>{{ selfFormData.phoneNum }}</span>
            </el-form-item>
            <el-form-item label="主诉：" prop="chiefComplaint">
                <el-input v-if="formType === 'edit' || formType === 'template'" placeholder="主诉" v-model="selfFormData.chiefComplaint" :disabled="stage !== 1 || formType === 'template'"
                    type="textarea" />
                <span v-else>{{ selfFormData.chiefComplaint }}</span>
            </el-form-item>
            <el-form-item label-width="0px" prop="assess">
                <table border class="form_table">
                    <colgroup>
                        <col style="width: 150px;">
                        <col style="width: 200px;">
                        <col style="width: 200px;">
                        <col style="width: 200px;">
                    </colgroup>
                    <thead>
                        <tr>
                            <th class="text_center">项目名称</th>
                            <th class="text_center">治疗前</th>
                            <th class="text_center">治疗中</th>
                            <th class="text_center">治疗后</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in assessFormStruct1" :key="'assess1_' + index">
                            <td class="text_center">{{ item.content }}</td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.beforeKey]"
                                    :disabled="stage !== 1 || formType === 'template'" class="score_radio" @input="calcTotal(1)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                    <el-radio :label="3" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.beforeKey] }}</span>
                            </td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.processKey]"
                                    :disabled="stage !== 2 || formType === 'template'" class="score_radio" @input="calcTotal(2)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                    <el-radio :label="3" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.processKey] }}</span>
                            </td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.afterKey]"
                                    :disabled="stage !== 3 || formType === 'template'" class="score_radio" @input="calcTotal(3)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                    <el-radio :label="3" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.afterKey] }}</span>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text_center">
                                <span class="score_item">0分：无自主运动</span>
                                <span class="score_item">1分：稍有自主运动</span>
                                <span class="score_item">2分：运动减弱</span>
                                <span class="score_item">3分：与侧腿基本相同</span>
                            </td>
                        </tr>
                        <tr v-for="(item, index) in assessFormStruct2" :key="'assess2_' + index">
                            <td class="text_center">{{ item.content }}</td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.beforeKey]"
                                    :disabled="stage !== 1 || formType === 'template'" class="score_radio" @input="calcTotal(1)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.beforeKey] }}</span>
                            </td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.processKey]"
                                    :disabled="stage !== 2 || formType === 'template'" class="score_radio" @input="calcTotal(2)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.processKey] }}</span>
                            </td>
                            <td class="text_center">
                                <el-radio-group v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.afterKey]"
                                    :disabled="stage !== 3 || formType === 'template'" class="score_radio" @input="calcTotal(3)">
                                    <el-radio :label="0" />
                                    <el-radio :label="1" />
                                    <el-radio :label="2" />
                                </el-radio-group>
                                <span v-else>{{ selfFormData[item.afterKey] }}</span>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text_center">
                                <span class="score_item">差：0分</span>
                                <span class="score_item">良：1分</span>
                                <span class="score_item">优：2分</span>
                            </td>
                        </tr>
                        <tr v-for="(item, index) in assessFormStruct3" :key="'assess3_' + index">
                            <td class="text_center">{{ item.content }}</td>
                            <td :colspan="item.merge ? 3 : 1">
                                <template v-if="item.beforeKey === 'treatmentNum'">
                                    <el-input v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.beforeKey]" disabled
                                        type="textarea" :rows="5" />
                                    <div v-else style="padding-left: 15px;">
                                        <div v-for="(treatment, treatIndex) in selfFormData.treatmentNumDetail"
                                            :key="'treat' + treatIndex">{{ treatment.treatmentName }}：{{
                                                treatment.treatmentNum }}次</div>
                                    </div>
                                </template>
                                <template v-else>
                                    <el-input v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.beforeKey]" disabled
                                        style="width: 180px;" />
                                    <div v-else style="width: 180px; text-align: center;">{{
                                        selfFormData[item.beforeKey] }}</div>
                                </template>
                            </td>
                            <td v-if="!item.merge" class="text_center">
                                <el-input v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.processKey]" disabled />
                                <span v-else>{{ selfFormData[item.processKey] }}</span>
                            </td>
                            <td v-if="!item.merge" class="text_center">
                                <el-input v-if="formType === 'edit' || formType === 'template'" v-model="selfFormData[item.afterKey]" disabled />
                                <span v-else>{{ selfFormData[item.afterKey] }}</span>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                注：评分表采用portmann简易评分法评分，分为6个项目，分别为皱眉、闭眼、动鼻翼、吹口哨、微笑、鼓腮；每项3分，共18分，加上安静时印象分2分，共20分。
                            </td>
                        </tr>
                    </tbody>
                </table>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import moment from 'moment'

const valueArray = ['frownValue', 'closeEyeValue', 'nasalValue', 'whistleValue', 'smileValue', 'bulgingValue', 'quietValue']
const initDefaultForm = () => {
    const assessTable = {}
    for (let stage = 1; stage <= 3; stage++) {
        for (let valIndex = 1; valIndex <= 7; valIndex++) {
            assessTable['stage' + stage + '_value' + valIndex] = undefined
        }
        assessTable['stage' + stage + '_total'] = ''
        assessTable['stage' + stage + '_createUser'] = ''
        assessTable['stage' + stage + '_createTime'] = ''
    }
    return {
        addr: '',
        phoneNum: '',
        chiefComplaint: '',
        treatmentNum: '',
        ...assessTable
    }
}
const assessFormStruct1 = [
    {
        content: '皱眉',
        beforeKey: 'stage1_value1',
        processKey: 'stage2_value1',
        afterKey: 'stage3_value1'
    },
    {
        content: '闭眼',
        beforeKey: 'stage1_value2',
        processKey: 'stage2_value2',
        afterKey: 'stage3_value2'
    },
    {
        content: '动鼻翼',
        beforeKey: 'stage1_value3',
        processKey: 'stage2_value3',
        afterKey: 'stage3_value3'
    },
    {
        content: '吹口哨',
        beforeKey: 'stage1_value4',
        processKey: 'stage2_value4',
        afterKey: 'stage3_value4'
    },
    {
        content: '微笑',
        beforeKey: 'stage1_value5',
        processKey: 'stage2_value5',
        afterKey: 'stage3_value5'
    },
    {
        content: '鼓腮',
        beforeKey: 'stage1_value6',
        processKey: 'stage2_value6',
        afterKey: 'stage3_value6'
    }
]
const assessFormStruct2 = [
    {
        content: '安静时印象分',
        beforeKey: 'stage1_value7',
        processKey: 'stage2_value7',
        afterKey: 'stage3_value7'
    }
]
const assessFormStruct3 = [
    {
        content: '总分',
        beforeKey: 'stage1_total',
        processKey: 'stage2_total',
        afterKey: 'stage3_total'
    },
    {
        content: '治疗次数',
        beforeKey: 'treatmentNum',
        merge: true
    },
    {
        content: '评定者签名',
        beforeKey: 'stage1_createUser',
        processKey: 'stage2_createUser',
        afterKey: 'stage3_createUser'
    },
    {
        content: '签名时间',
        beforeKey: 'stage1_createTime',
        processKey: 'stage2_createTime',
        afterKey: 'stage3_createTime'
    }
]
export default {
    name: 'FacialNerve',
    props: {
        formType: {
            type: String,
            default: 'template' // 表单类型：template：模板，edit：评估，view：详情
        },
        patientInfo: {
            type: Object,
            default: () => ({}) // 患者信息
        },
        doctorType: {
            type: String,
            default: 'hospital' // 医生类型：hospital：住院医生，outpatient：门诊医生，therapists：治疗师
        },
        assessInfo: {
            type: Object,
            default: () => ({}) // 评定表信息
        }
    },
    data() {
        return {
            assessFormStruct1,
            assessFormStruct2,
            assessFormStruct3,
            selfFormData: {},
            rules: {
                addr: [
                    { required: true, message: '请输入通讯地址', trigger: 'blur' }
                ],
                phoneNum: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' }
                ],
                chiefComplaint: [
                    { required: true, message: '请输入主诉', trigger: 'blur' }
                ],
                assess: [
                    { validator: this.validateAssess, trigger: 'change' }
                ]
            },
            stage: 0
        }
    },
    computed: {
        patientStruct() {
            if (this.formType === 'edit' || this.formType === 'view') {
                return [{
                    label: '姓名',
                    key: 'patientName'
                }, {
                    label: '性别',
                    key: 'genderName'
                }, {
                    label: '年龄',
                    key: 'age',
                    unit: '岁'
                }, {
                    label: '科室',
                    key: 'departmentName'
                }, {
                    label: ['hospital', 'therapists'].includes(this.doctorType) ? '门诊号/住院号' : '门诊号',
                    key: 'admissionNum'
                }]
            } else {
                return [{
                    label: '姓名',
                    key: ''
                }, {
                    label: '性别',
                    key: ''
                }, {
                    label: '年龄',
                    key: ''
                }, {
                    label: '科室',
                    key: ''
                }, {
                    label: '门诊号/住院号',
                    key: ''
                }]
            }
        }
    },
    watch: {
        assessInfo: function (val) {
            this.initFormData()
        }
    },
    mounted() {
        this.initFormData()
    },
    methods: {
        initFormData() {
            const assessTable = {}
            this.stage = 0
            if (this.assessInfo.evaluateDetail && this.assessInfo.evaluateDetail.length) {
                this.assessInfo.evaluateDetail.forEach(item => {
                    Object.keys(item).forEach(key => {
                        const index = valueArray.findIndex(item => item === key)
                        if (index >= 0) {
                            assessTable['stage' + item.estimateType + '_value' + (index + 1)] = item[key]
                        }
                    })
                    if (item.estimateType > this.stage) {
                        this.stage = item.estimateType
                    }
                    assessTable['stage' + item.estimateType + '_total'] = item.totalValue
                    assessTable['stage' + item.estimateType + '_createUser'] = item.evaluateUser
                    assessTable['stage' + item.estimateType + '_createTime'] = moment(item.evaluateTime).format('YYYY-MM-DD HH:mm:ss')
                })
            }
            if (this.stage <= 2) {
                this.stage += 1
            }
            if (!assessTable['stage' + this.stage + '_createUser'] || !assessTable['stage' + this.stage + '_createTime']) {
                assessTable['stage' + this.stage + '_createUser'] = this.assessInfo.evaluateUser
                assessTable['stage' + this.stage + '_createTime'] = this.assessInfo.evaluateTime
            }
            if (this.assessInfo.treatmentNumDetail) {
                assessTable.treatmentNum = this.assessInfo.treatmentNumDetail.map(item => item.treatmentName + '：' + item.treatmentNum + '次').join('\n')
            }
            this.selfFormData = Object.assign(initDefaultForm(), this.assessInfo, assessTable)

            console.log(this.selfFormData, '1231231');
        },
        calcTotal(_stage) {
            let total = 0
            for (let valIndex = 1; valIndex <= 7; valIndex++) {
                total += (this.selfFormData['stage' + _stage + '_value' + valIndex] || 0)
            }
            this.selfFormData['stage' + _stage + '_total'] = total
        },
        getFormData() {
            return new Promise((resolve, reject) => {
                this.$refs.assessForm.validate((valid) => {
                    if (valid) {
                        const submitForm = {}
                        Object.keys(this.selfFormData).forEach(key => {
                            if (key.startsWith('stage' + this.stage + '_value')) {
                                const index = parseInt(key.replace('stage' + this.stage + '_value', ''))
                                submitForm[valueArray[index - 1]] = this.selfFormData[key]
                            }
                        })
                        submitForm.phoneNum = this.selfFormData.phoneNum
                        submitForm.addr = this.selfFormData.addr
                        submitForm.chiefComplaint = this.selfFormData.chiefComplaint
                        resolve({
                            ...submitForm
                        })
                    } else {
                        reject('存在未通过表单校验的数据')
                        return false
                    }
                })
            })
        },
        changeToEstimateList(estimateId, submitForm) {
            const keyList = []
            Object.keys(submitForm).forEach(key => {
                if(submitForm[key]){
                    keyList.push({
                        key,
                        value: JSON.stringify(submitForm[key])
                    })
                }
            })
            return JSON.stringify({
                estimateId,
                keyList
            })
        },
        async saveLocalFormData(source, patientId) {
            let data = await this.getFormData();
            const estimateId = 3
            const submitForm = {
                evaluateSource: source,
                ...data
            }
            localStorage.setItem(`estimate_${source}_${patientId}_${estimateId}`, this.changeToEstimateList(estimateId, submitForm)); 
        },
        validateAssess(rule, value, callback) {
            for (let valIndex = 1; valIndex <= 7; valIndex++) {
                if (this.selfFormData['stage' + this.stage + '_value' + valIndex] === undefined) {
                    if (valIndex === 7) {
                        callback('请选择安静时印象分')
                    } else {
                        const item = assessFormStruct1[valIndex - 1]
                        callback('请选择' + item.content + '的分数')
                    }
                    return
                }
            }
            callback()
        }
    }
}
</script>

<style lang="scss" scoped>
@import url('./style.scss');

.facial_nerve {
    .form_patient_info {
        border-top: 1px solid #333;
        padding-top: 10px;

        .info_item {
            display: flex;
            margin-bottom: 5px;

            .info_label {
                text-align: right;
                width: 80px;
            }
        }
    }

    .score_item {
        margin-right: 20px;

        &:last-child {
            margin-right: 0;
        }
    }

    .score_radio {
        .el-radio {
            margin-right: 10px;
        }
    }
}
</style>
